import base64
from werkzeug.datastructures import FileStorage

from .BaseConvert import Convert


class BinaryConvert(Convert):
    field_type = 'binary'

    @classmethod
    def to_read(cls, rec, field, **kwargs):
        if isinstance(rec[field.name], bytes):
            # utf-8
            value = str(rec[field.name], encoding='utf-8')
        else:
            value = rec[field.name] or ''

        return value

    @classmethod
    def to_field(cls, value, metadata=None, update=False):
        if value:
            if isinstance(value, FileStorage):
                return base64.b64encode(value.read())

            return b'' if value in ['undefined', 'null'] else value

        return b''
